package com.hzhc.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.entity.TrainPlanCity;
import com.hzhc.entity.TrainPlanDetail;
import com.hzhc.mapper.StationMapper;
import com.hzhc.mapper.TrainPlanCityMapper;
import com.hzhc.mapper.TrainPlanDetailMapper;
import com.hzhc.service.TrainPlanCityService;
import com.hzhc.utils.BeanUtils;
import com.hzhc.utils.StringUtils;
import com.hzhc.vo.TrainPlanDetailVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 进站登记箱城市统计表 服务实现类
 * </p>
 *
 * @author 功不唐捐
 * @since 2024-09-27
 */
@Service
@RequiredArgsConstructor
public class TrainPlanCityServiceImpl extends ServiceImpl<TrainPlanCityMapper, TrainPlanCity> implements TrainPlanCityService {

    private final StationMapper stationMapper;
    private final TrainPlanDetailMapper trainPlanDetailMapper;
    // 高德地图key
    public static final String KEY = "6dc239658cd94e2007b4f3c933106693";

    @Override
    public void updateCityCntr() {
        //获取旧数据
        List<TrainPlanCity> oldTrainPlanCityList = baseMapper.selectList(Wrappers.<TrainPlanCity>lambdaQuery()
                .eq(TrainPlanCity::getDisable, 0));
        //获取最新数据
        List<TrainPlanDetailVo> detailVoList=trainPlanDetailMapper.selectPortList();
        List<TrainPlanCity>  list = new ArrayList<>();
        List<TrainPlanDetail> lhList=new ArrayList<>();
        for (TrainPlanDetailVo trainPlanDetailVo : detailVoList) {
            TrainPlanDetail trainPlanDetail=new TrainPlanDetail();
            if(StringUtils.isEmpty(trainPlanDetailVo.getSignLx())){
                trainPlanDetailVo.setZhPort(trainPlanDetailVo.getEndPort());
            }
            BeanUtils.copyProperties(trainPlanDetailVo,trainPlanDetail);
            lhList.add(trainPlanDetail);
        }
        Map<String, List<TrainPlanDetail>> collect = lhList.stream().filter(s -> StringUtils.isNotEmpty(s.getZhPort())).collect(Collectors.groupingBy(TrainPlanDetail::getZhPort));

        for (Map.Entry<String, List<TrainPlanDetail>> entry : collect.entrySet()) {
            Integer xcSum=0;
            Integer zcSum=0;
            List<TrainPlanDetail> xcCntr = entry.getValue().stream().filter(s -> StringUtils.isNotEmpty(s.getSignLx())).collect(Collectors.toList());
            List<TrainPlanDetail> zcCntr = entry.getValue().stream().filter(s -> StringUtils.isEmpty(s.getSignLx())).collect(Collectors.toList());
            if(xcCntr.size()>0){
                for (TrainPlanDetail trainPlanDetail : xcCntr) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        xcSum++;
                    }else{
                        xcSum = xcSum +2;
                    }
                }
            }
            if(zcCntr.size()>0){
                for (TrainPlanDetail trainPlanDetail : zcCntr) {
                    if(trainPlanDetail.getCntrSize().startsWith("2")){
                        zcSum++;
                    }else{
                        zcSum = zcSum +2;
                    }
                }
            }
            TrainPlanCity city=new TrainPlanCity();
            List<TrainPlanCity> trainPlanCities = oldTrainPlanCityList.stream().filter(s -> s.getCity().equals(entry.getKey())).collect(Collectors.toList());
            city.setCity(entry.getKey());
            city.setCreateTime(LocalDateTime.now());
            city.setFyCntrNum(String.valueOf(zcSum));
            city.setDdCntrNum(String.valueOf(xcSum));
            if(trainPlanCities.size()>0){
                city.setId(trainPlanCities.get(0).getId());
            }else{
                getPoint(city);
            }
            list.add(city);
        }
        saveOrUpdateBatch(list);
    }

    @Override
    public List<TrainPlanCity> getDpLine(TrainPlanCity trainPlanCity) {
        List<TrainPlanCity> trainPlanCities = baseMapper.selectList(new QueryWrapper<TrainPlanCity>().eq("disable", 0));
        List<TrainPlanCity> cities=new ArrayList<>();
        for (TrainPlanCity planCity : trainPlanCities) {
            if(StringUtils.isNotEmpty(planCity.getCity())){
                cities.add(planCity);
            }
        }
        return cities;
    }

    public void getPoint(TrainPlanCity city) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://restapi.amap.com/v3/geocode/geo?";
        url += "key=" + KEY + "&s=rsv3&address=" + city.getCity();
        try {
            JSONObject ret = restTemplate.getForObject(url, JSONObject.class);
            if(!ret.containsKey("status")){
                return;
            }
            if(!ret.containsKey("geocodes")){
                return;
            }
            Integer status = ret.getInt("status");
            if(status == null){
                return;
            }
            JSONArray geocodes = ret.getJSONArray("geocodes");
            if(geocodes == null || geocodes.isEmpty()){
                return;
            }
            JSONObject jsonObject = geocodes.getJSONObject(0);
            if(!jsonObject.containsKey("location")){
                return;
            }
            String location = jsonObject.getStr("location");
            String[] locations = location.split(",");
            city.setLng(locations[0]).setLat(locations[1]);
        }catch (Exception e) {
            //e.printStackTrace();
        }
    }

}
